#include "sourcefile.h"

/**
 * Loads the specified file into this object
 *
 * @param *filename file to load
 */
SourceFile::SourceFile(char *filename) {
	_filename = new char[strlen(filename)];
	strcpy(_filename, filename);
	load();
}

SourceFile::~SourceFile() {
	_lines.clear();
	delete _filename;
}

/**
 * Loads a new file into the _lines buffer. Old contents is thrown out.
 *
 * @param *filename file to load
 */
void SourceFile::loadNew(char *filename) {
	delete _filename;
	_lines.clear();
	_filename = new char[strlen(filename)];
	strcpy(_filename, filename);
	load(filename);
}

/**
 * Wrapper for the load function. Calls load with the current filename
 */
void SourceFile::load(void) {
	load(_filename);
}

/**
 * Loads the specified file.
 *
 * NOTE: keeps what is currently in _lines there. So it appends the newfile on
 *       the end. If you want to open a totally new file, use loadNew(..).
 *
 * @param *filename the file to load
 */
void SourceFile::load(char *filename) {
	ifstream file(filename);
	while(file.is_open()) {
		while(!file.eof()) {
			string line;
			getline(file, line);
			_lines.push_back(line);
		}
		file.close();
	}
}

/**
 * Gets a single line from the file.
 *
 * @param lineNum the line to get
 * @return the line
 */
const string *SourceFile::getLine(int lineNum) const {
	if (lineNum < numLines()) {
		return &_lines[lineNum];
	}
}

/**
 * Returns a vector of strings, which are the file contents
 * 
 * @return vector of strings
 */
const vector<string> *SourceFile::getLines(void) const {
	return &_lines;
}

/**
 * Returns the number of lines (including whitespace and comments)
 *
 * @return number of lines
 */
int SourceFile::numLines(void) const {
	return _lines.size()-1;
}
